<template>
  <div class="home" style="height:calc(100vh - 64px)">
    <Row type="flex" justify="center" :gutter="20">
      <!-- 左侧开始 -->
      <i-col :span="16">
        <Row style="margin: 30px 10px 10px 10px;">
          <MyForm
            ref="myForm"
            :subCompanyList="subCompanyList"
            :stationList="selectedStationList"
            :categoryList="categoryList"
            :channelList="selectedChannelList"
            @changeSubCompany="changeStationList"
            @changeStationAndCategory="changeChannelList"
            @handleSearchMonitor="handleSearchMonitor"
            style="text-align:left;color:#fff"
          ></MyForm>
        </Row>
        <Row style="margin: 80px 10px auto 10px;">
          <MyVideo :videoInfo="videoInfo"></MyVideo>
        </Row>
      </i-col>
      <!-- 左侧结束 -->
      <!-- 右侧开始 -->
      <i-col :span="8">
        <Row style="margin-top:30px;">
          <MyStatistics :statisticsList="statisticsList"></MyStatistics>
        </Row>

        <Row style="margin-top:30px;">
          <MyTable :tableData="noticeList"> </MyTable>
        </Row>
      </i-col>
      <!-- 右侧结束 -->
    </Row>
  </div>
</template>

<script>
// 常量
import constData from "@/util/constData2";
// 工具
import axios from "axios";
import dayjs from "dayjs";
// 页面组件
import MyForm from "./myForm.vue";
import MyVideo from "./myVideo.vue";
import MyStatistics from "./myStatistics.vue";
import MyNotice from "./myNotice.vue";
import MyTable from "./myTable.vue";
import {
  reqEvent,
  reqStatistic,
  reqServiceStatistic,
  reqCustomerEnter,
  reqViolateNow
} from "@/api";
var node_schedule = require("node-schedule");

export default {
  name: "home",
  components: {
    MyForm,
    MyVideo,
    MyStatistics,
    MyNotice,
    MyTable
  },
  data() {
    return {
      // 选项数据
      subCompanyList: constData.subCompanyList,
      subCompanyData: constData.subCompanyData,
      stationList: constData.stationList,
      selectedStationList: [],
      stationData: constData.stationData,
      categoryList: constData.categoryList,
      categoryData: constData.categoryData,
      channelList: constData.channelList,
      selectedChannelList: [],
      channelData: {},
      levelList: constData.levelList,
      levelData: constData.levelData,

      // 视频
      /**
       * demo:
       * videoInfo: { value: "", title: "", videoSrc: "" }
       */
      videoInfo: {},

      // 统计
      statisticsList: [],

      // 事件
      noticeList: [],
      pageCurrent: 1,
      pageSize: 50,
      //查看事件图片
      videoModal: false,
      eventDetailList: [],

      currentStation: ''
    };
  },
  created() {
    console.log('监控：', this.$route)
    if (this.$route.params.station) {
      this.currentStation = this.$route.params.station.value;
    }
  },
  mounted() {
    // var intervalRightStation = node_schedule.scheduleJob(
    //   "*/5 * * * * *",
    //   () => {
    //     console.log("事件统计每5秒刷新一次");
    //     let start_time = dayjs()
    //       .startOf()
    //       .format("YYYY-MM-DD 00:00:00");
    //     let end_time = dayjs().format("YYYY-MM-DD 23:59:59");
    //     let page_index = this.pageCurrent;
    //     let page_size = this.pageSize;
    //     let station = this.$refs.myForm.station;
    //     let category = this.$refs.myForm.category;
    //     let channel = this.$refs.myForm.channel;

    //     if (
    //       station != undefined &&
    //       category != undefined &&
    //       channel != undefined
    //     ) {
    //       this.getStatisticsList(station, channel, category);
    //       this.getTableData(
    //         start_time,
    //         end_time,
    //         station,
    //         channel,
    //         page_index,
    //         page_size
    //       );
    //     }
    //   }
    // );
    // 通过$once来监听定时器，在beforeDestroy钩子可以被清除。
    this.$once("hook:beforeDestroy", () => {
      // console.log("取消事件统计刷新");
      intervalRightStation.cancel();
    });
  },
  methods: {
    changeStationList(subCompany) {
      this.selectedStationList = [];
      var index;
      var station;
      for (index in this.stationList) {
        station = this.stationList[index];
        if (subCompany === station.subCompany) {
          this.selectedStationList.push(station);
        }
      }
    },
    changeChannelList(stationAndCategory) {
      var station = stationAndCategory.station;
      var category = stationAndCategory.category;
      this.selectedChannelList = [];
      this.channelData = {};
      var index;
      var channel;
      if (category === "") {
        for (index in this.channelList) {
          channel = this.channelList[index];
          if (station === channel.station) {
            this.selectedChannelList.push(channel);
            this.channelData[channel.value] = channel.label;
          }
        }
      } else {
        for (index in this.channelList) {
          channel = this.channelList[index];
          if (station === channel.station && category === channel.category) {
            this.selectedChannelList.push(channel);
            this.channelData[channel.value] = channel.label;
          }
        }
      }
    },
    handleSearchMonitor(value) {
      console.log("收集表单数据：", value);

      this.formData = value;
      let station = value.station;
      let channel = value.channel;

      // 请求数据
      this.getVideoData(station, channel);
      this.handleSearchNotice(value);
    },
    getVideoData(station, channel) {
      axios
        .get("http://10.202.5.9:5123/datacenter/stream/pull", {
          params: {
            station: station,
            channel: channel
          }
        })
        .then(res => {
          // console.log("得到响应数据：", res);

          let resData = res.data.data;
          let videoData = {
            value:
              resData.station +
              " - " +
              resData.category +
              " - " +
              resData.channel,
            title:
              this.stationData[resData.station] +
              " - " +
              this.categoryData[resData.category] +
              " - " +
              this.channelData[resData.channel],
            videoSrc: resData.streamUrl,
            flvsrc: resData.httpflvUrl
          };
          this.videoInfo = videoData;
        });
    },
    handleSearchNotice(value) {
      //console.log(value)
      let station = value.station === "all" ? "" : value.station;
      let channel = value.channel === "" ? "1" : value.channel;
      let category = value.category === "" ? "checkout" : value.category;
      let start_time = dayjs()
        .startOf()
        .format("YYYY-MM-DD 00:00:00");
      let end_time = dayjs().format("YYYY-MM-DD 23:59:59");
      let page_index = this.pageCurrent;
      let page_size = this.pageSize;

      this.getTableData(
        start_time,
        end_time,
        station,
        channel,
        page_index,
        page_size
      );
      this.getStatisticsList(station, channel, category);
    },
    getTableData(
      start_time,
      end_time,
      station,
      channel,
      page_index,
      page_size
    ) {
      let params = {
        start_time,
        end_time,
        station,
        channel,
        page_index,
        page_size
      };
      //console.log(params)
      reqEvent(params).then(res => {
        let resData = res.data.events;
        let tableData = resData.map((ele, index) => {
          return {
            index: index + 1,
            station: this.stationData[ele.station],
            action: ele.action,
            cause: ele.cause,
            level: this.levelData[ele.level],
            status: ele.status,
            datetime: ele.datetime,
            http_url_image: ele.http_url_image,
            videoModal: this.videoModal
          };
        });
        this.noticeList = tableData;
      });
    },

    //获取各个场景的统计事件数据
    getStatisticsList(station, channel, category) {
      if (category === "checkout") {
        this.getCheckoutData("day", station, channel, category);
      } else if (category === "safebox") {
        this.getSafeBoxData("day", station, channel, category);
      } else if (category === "gate") {
        this.getGateData("day", station, channel, category);
      } else if (category === "refuel_side") {
        this.getRefuelSideData("day", station, channel, category);
      } else if (category === "unload") {
        this.getUnloadData("day", station, channel, category);
      } else if (category === "refuel_overview") {
        this.getRefuelOverviewData("day", station, 4, "refuel_side");
      }
    },
    // 获取保险柜数据
    getSafeBoxData(group, station, channel, category) {
      let start_time = dayjs()
        .startOf()
        .format("YYYY-MM-DD 00:00:00");
      let end_time = dayjs().format("YYYY-MM-DD 23:59:59");
      let paramsSafebox = {
        start_time,
        end_time,
        group,
        channel,
        station,
        category,
        action: "开启保险柜"
      };
      let paramsMoneybox = {
        start_time,
        end_time,
        group,
        channel,
        station,
        category,
        action: "开启钱箱"
      };
      let paramsViolation = {
        station,
        category
      };
      // console.log(paramsViolation.station + paramsViolation.category);
      let safebox = [];
      //safebox['category'] = "safebox"
      safebox.push("safebox");
      reqStatistic(paramsSafebox).then(res => {
        let safeboxOpenTotalNum = res.data.total_num;
        safebox.push(safeboxOpenTotalNum);
        //safebox['safeboxOpenTotalNum'] = safeboxOpenTotalNum
        reqStatistic(paramsMoneybox).then(res => {
          let moneyboxOpenTotalNum = res.data.total_num;
          safebox.push(moneyboxOpenTotalNum);
          //safebox['moneyboxOpenTotalNum'] = moneyboxOpenTotalNum
          reqViolateNow(paramsViolation).then(res => {
            if (res.code === 9000) {
              safebox.push(0);
            } else {
              let violationRate = res.data.general;

              safebox.push(Math.round(violationRate * 1000) / 10);
            }
            // console.log("violationRate:" + safebox[3]);
            this.statisticsList = safebox;
          });
        });
      });
    },
    // 获取便利店数据统计
    getCheckoutData(group, station, channel, category) {
      let start_time = dayjs()
        .startOf()
        .format("YYYY-MM-DD 00:00:00");

      let end_time = dayjs()
        .add(1, "day")
        .format("YYYY-MM-DD 00:00:00");

      let paramsCheckout = {
        start_time,
        end_time,
        group,
        channel,
        station,
        category,
        interval: 1
      };
      let paramsViolation = {
        station,
        category
      };

      let checkout = [];
      checkout.push("checkout");
      reqServiceStatistic(paramsCheckout).then(res => {
        let serverTotalNum = res.data.count_all;
        console.log("serverTotalNum:" + serverTotalNum);
        checkout.push(serverTotalNum);
        reqViolateNow(paramsViolation).then(res => {
          let violationRate = res.data.general;
          checkout.push(Math.round(violationRate * 1000) / 10);
          this.statisticsList = checkout;
        });
      });
      //this.statisticsList = checkout;
    },
    //获取加油现场的数据统计
    getRefuelSideData(group, station, channel, category) {
      let start_time = dayjs()
        .startOf()
        .format("YYYY-MM-DD 00:00:00");

      let end_time = dayjs()
        .add(1, "day")
        .format("YYYY-MM-DD 00:00:00");

      let paramsRefuelSide = {
        start_time,
        end_time,
        group,
        channel,
        station,
        interval: 1,
        category
      };

      let refuel_side = [];
      refuel_side.push("refuel_side");
      reqServiceStatistic(paramsRefuelSide).then(res => {
        let vehicleTotalNum = res.data.count_all;
        let vehicleAverage = res.data.average_all;
        refuel_side.push(vehicleTotalNum);
        // console.log("vehicleAverage:" + vehicleAverage);
        if (vehicleAverage === undefined) {
          refuel_side.push("暂无服务时间");
        } else {
          let s = vehicleAverage % 60;
          let m = Math.floor(vehicleAverage / 60);

          refuel_side.push(m + "分 " + s + "秒");
        }
        this.statisticsList = refuel_side;
        // console.log(this.statisticsList);
      });
      //this.statisticsList = refuel_side;
    },
    //获取便利店大门数据统计
    getGateData(group, station, channel, category) {
      let start_time = dayjs()
        .startOf()
        .format("YYYY-MM-DD 00:00:00");

      let end_time = dayjs()
        .add(1, "day")
        .format("YYYY-MM-DD 00:00:00");

      let paramsGate = {
        start_time,
        end_time,
        group,
        channel,
        station,
        interval: 1
      };

      let gate = [];
      gate.push("gate");
      reqCustomerEnter(paramsGate).then(res => {
        let enterTotalNum = res.data.count_all;
        gate.push(enterTotalNum);
        this.statisticsList = gate;
      });
    },
    getViolationEventTotal() {},
    getUnloadData(group, station, channel, category) {
      let start_time = dayjs()
        .startOf()
        .format("YYYY-MM-DD 00:00:00");

      let end_time = dayjs()
        .add(1, "day")
        .format("YYYY-MM-DD 00:00:00");

      let paramsViolation = {
        start_time,
        end_time,
        group,
        channel,
        station,
        category,
        status: "违规"
      };

      let unload = [];
      unload.push("unload");
      reqStatistic(paramsViolation).then(res => {
        let violationTotalNum = res.data.total_num;
        unload.push(violationTotalNum);
        this.statisticsList = unload;
      });
    },
    getRefuelOverviewData(group, station, channel, category) {
      let start_time = dayjs()
        .startOf()
        .format("YYYY-MM-DD 00:00:00");

      let end_time = dayjs()
        .add(1, "day")
        .format("YYYY-MM-DD 00:00:00");

      let paramsRefuelSide = {
        start_time,
        end_time,
        group,
        station,
        interval: 1,
        category
      };
      let paramsViolation = {
        station,
        category
      };

      // console.log("paramsViolation:" + paramsViolation);
      // console.log("paramsEvent:" + paramsEvent);
      let refuel_overview = [];
      refuel_overview.push("refuel_overview");
      reqServiceStatistic(paramsRefuelSide).then(res => {
        let vehicleTotalNum = res.data.count_all;
        refuel_overview.push(vehicleTotalNum);
        reqViolateNow(paramsViolation).then(res => {
          let violationRate = res.data.general;
          // console.log("violationRate:" + violationRate);
          refuel_overview.push(Math.round(violationRate * 1000) / 10);
          this.statisticsList = refuel_overview;
        });
      });
    }
    // getViolationEventTotal() {}
  }
};
</script>

<style lang="less">
.ivu-card-bordered {
  border: 1px solid #0a4271 !important;
  border-color: #0a4271 !important;
}
.ivu-card-head {
  padding: 4px 15px !important;
  border-bottom: 1px solid #0b0f34 !important;
  /* background-color: #13a4c2 !important; */
  background-color: #0b0f34 !important;
  background-image: url("../../assets/title-bg.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  height: 60px;
}
.ivu-card-head p {
  font-size: 2.4rem !important;
  height: 60px !important;
  line-height: 60px !important;
  // margin-top: 4px;
  color: #fff !important;
  text-align: left;
}
.ivu-card-body {
  padding: 0px !important;
}
.count-style {
  font-size: 50px;
  color: #fff;
}
.select {
  font-size: 1.6rem;
  margin-left: 20px;
}
.select a {
  color: #fff;
}
.ivu-dropdown-item {
  color: #fff;
}
.ivu-select-selection {
  width: 150px;
  background-color: #1770bb7a !important;
  border: 1px solid #2d6696 !important;
}
.ivu-select-dropdown {
  background-color: #0e246d !important;
}
</style>
